#include <stdio.h>
#include <stdlib.h>
#include "mrj_supt.h"
#include "mpx_supt.h"
#include "r3.h"
#include <dos.h>

void load_process(char*, int);
int strint(char*);


void load_process(char* prgm_name, int priority){
	pcb* fresh;
	int APP_CLASS = 1;
	int error_code;
	int prgm_size;
	int start_offset_p;
	context* cp;
	unsigned char* load_address;
	unsigned char* execution_address;
	char* prgm_dir = "\0";  //current directory
	
	

	error_code = sys_check_program(prgm_dir, prgm_name, &prgm_size, &start_offset_p);
	//printf("sys_check_progam error_code: %d\n", error_code);
		load_address = (unsigned char*) sys_alloc_mem(prgm_size*sizeof(unsigned char));
	
	
	execution_address = load_address + start_offset_p;
	
	if(priority == -128){APP_CLASS = 0;}  //If IDLE process, class is set to SYSTEM
	
	fresh = setPCB(prgm_name, priority, APP_CLASS);
	
	if((error_code == 0) && fresh){
		fresh->susp = PCB_FLAG_SUSP;
		fresh->state = PCB_STATE_RDY;
		fresh->locAddr = load_address;
		fresh->excAddr = execution_address;
		fresh->memSize = prgm_size;
		if(priority == -128){fresh->susp = 0;} //Do not suspend if IDLE process
		enqueueReady(fresh);
	}else{
		printf("Error encountered while attempting to load process.\n Request not completed.\n");
	}
	error_code = sys_load_program(load_address, PCB_STACK_SIZE, prgm_dir, prgm_name);
	//printf("sys_load_program error_code: %d\n", error_code);
	
	cp = (context *) fresh->stackT;
		
	cp->IP = FP_OFF(execution_address);
	cp->CS = FP_SEG(execution_address);
	cp->FLAGS = 0x200;
	cp->DS = _DS;
	cp->ES = _ES;
}



int free_pcb(pcb *freebird){
	int error_code;
	error_code = sys_free_mem(freebird->locAddr);
	//printf("free_pcb load address error_code: %d\n", error_code);
	error_code = sys_free_mem(freebird);
	//printf("free_pcb pcb error_code: %d\n", error_code);
	
	return error_code;
}